package xyz.molzhao.handler;

import cn.hutool.core.text.CharSequenceUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import xyz.molzhao.util.DataDesensitizationUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 敏感信息（例如:姓名/身份证/银行卡号）脱敏存入数据库
 * 本文采用AES加解密，实际情况可根据需要自行选择加解密方式
 * 数据库CRUD时如何使用？
 */
@Slf4j
public class SensitiveDataTypeHandler extends BaseTypeHandler<String> {
    /**
     * 密钥
     */
    private static final String ERROR = "SensitiveDataTypeHandler异常";

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        try {
            ps.setString(i, DataDesensitizationUtils.encrypt(parameter));
        } catch (Exception e) {
            log.info(ERROR, e);
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String columnValue = rs.getString(columnName);
        try {
            return CharSequenceUtil.isEmpty(columnValue) ? columnValue : DataDesensitizationUtils.decrypt(columnValue);
        } catch (Exception e) {
            log.info(ERROR, e);
            return columnValue;
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String columnValue = rs.getString(columnIndex);
        try {
            return CharSequenceUtil.isEmpty(columnValue) ? columnValue : DataDesensitizationUtils.decrypt(columnValue);
        } catch (Exception e) {
            log.info(ERROR, e);
            return columnValue;
        }
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String columnValue = cs.getString(columnIndex);
        try {
            return CharSequenceUtil.isBlank(columnValue) ? columnValue : DataDesensitizationUtils.decrypt(columnValue);
        } catch (Exception e) {
            log.info(ERROR, e);
            return columnValue;
        }
    }
}